﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using HandyControl.Controls;
using MiniExcelLibs;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Configuration;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Input;
using Zo.ExcelBox.Base;
using Zo.ExcelBox.Models;

namespace Zo.ExcelBox.ViewModels
{

    /// <summary>
    /// 模版编辑
    /// </summary>
    public partial class MapTemplateEditVM : ObservableObject
    {
        /// <summary>
        /// 表单数据
        /// </summary>
        public MapTemplate FormData { get; set; } = new MapTemplate();

        /// <summary>
        /// 模版映射字段
        /// </summary>
        //public ObservableCollection<MapTemplate_Config> FormDataTemplate { get; set; } = new ObservableCollection<MapTemplate_Config>();


        private ObservableCollection<MapTemplate_Config> _formDataTemplate = new ObservableCollection<MapTemplate_Config>();

        /// <summary>
        /// MVVM 必须这样写
        /// </summary>
        public ObservableCollection<MapTemplate_Config> FormDataTemplate
        {
            get => _formDataTemplate;
            set => SetProperty(ref _formDataTemplate, value);
        }


        /// <summary>
        /// 选择解析文件
        /// </summary>
        public ICommand OnSelectFileCommand { get; }


        /// <summary>
        /// 删除行
        /// </summary>
        public IRelayCommand<MapTemplate_Config> OnDeleteCommand { get; }

        /// <summary>
        /// 重置数据
        /// </summary>
        public IRelayCommand OnResetCommand { get; }


        /// <summary>
        /// 提交数据
        /// </summary>
        public IRelayCommand OnSubmitCommand { get; }

        /// <summary>
        /// 取消
        /// </summary>
        public IRelayCommand OnCancelCommand { get; }


        /// <summary>
        /// 请求关闭窗口 
        /// </summary>
        public event Action<WindowCloseType> RequestClose;




        private ObservableCollection<string> _ExcelFileSelect = new ObservableCollection<string>();

        /// <summary>
        /// excel字段
        /// </summary>
        public ObservableCollection<string> ExcelFileSelect
        {
            get => _ExcelFileSelect;
            set => SetProperty(ref _ExcelFileSelect, value);
        }


        /// <summary>
        /// 数据访问
        /// </summary>
        public static SqlSugarClient _db;


        /// <summary>
        /// 页面ID
        /// </summary>
        public int PageId { get; private set; }


        /// <summary>
        /// 读取json文件模版字段
        /// </summary>
        public static List<MapTemplate_Config> MapTemplateList = new List<MapTemplate_Config>();



        /// <summary>
        /// 
        /// </summary>
        public MapTemplateEditVM(int id)
        {

            PageId = id;

            OnSelectFileCommand = new RelayCommand(OnSelectFile);
            OnDeleteCommand = new RelayCommand<MapTemplate_Config>(OnDelete);
            OnResetCommand = new RelayCommand(OnReset);
            OnSubmitCommand = new RelayCommand(OnSubmit);
            OnCancelCommand = new RelayCommand(OnCancel);

            _db = new DbContext().DataBase;



            Get(id);
        }


        private void Get(int id)
        {
            if (id > 0)
            {
                FormData = _db.Queryable<MapTemplate>().Where(w => w.Id == id).First();
                FormDataTemplate = new ObservableCollection<MapTemplate_Config>(FormData.Template);
            }
            else
            {

                var t = AppContext.JsonConfig.ExcelColumnName.Select(s => new MapTemplate_Config { Source = s }).ToList();

                FormDataTemplate = new ObservableCollection<MapTemplate_Config>(t);
            }

        }

        /// <summary>
        /// 选中解析文件
        /// </summary>
        void OnSelectFile()
        {
            var openFileDialog = new OpenFileDialog
            {
                Title = "请选择 Excel 或 CSV 文件",
                Filter = "Excel 文件 (*.xls;*.xlsx)|*.xls;*.xlsx|CSV 文件 (*.csv)|*.csv",
                Multiselect = false
            };

            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                string filePath = openFileDialog.FileName;

                var extension = Path.GetExtension(filePath).ToLower();

                var excelType = ExcelType.UNKNOWN;
                MiniExcelLibs.Configuration config = null; 

                switch (extension)
                {
                    case ".csv":
                        excelType= ExcelType.CSV;
                        config = new MiniExcelLibs.Csv.CsvConfiguration()
                        {
                            StreamReaderFunc = (stream) => new StreamReader(stream, Encoding.GetEncoding("gb2312"))
                        };
                        break;
                    case ".xls":
                        excelType= ExcelType.XLSX;
                        break;
                    case ".xlsx":
                        excelType= ExcelType.XLSX;
                        break;
                }
                ExcelFileSelect = new ObservableCollection<string>(MiniExcel.GetColumns(filePath, useHeaderRow: true, excelType: excelType, configuration: config));

            }
        }



        /// <summary>
        /// 删除行  
        /// </summary>
        /// <param name="config"></param>
        void OnDelete(MapTemplate_Config config)
        {
            if (config != null)
            {
                FormDataTemplate.Remove(config);
            }
        }


        /// <summary>
        /// 重置数据
        /// </summary>
        void OnReset()
        {
            ExcelFileSelect.Clear();
        }

        /// <summary>
        /// 提交
        /// </summary>
        void OnSubmit()
        {

            FormData.Template = FormDataTemplate.Select(s => new MapTemplate_Config()
            {
                Source = s.Source,
                Target = s.Target
            }).ToList();

            var row = 0;
            if (PageId > 0)
            {
                row = _db.Updateable(FormData).ExecuteCommand();
            }
            else
            {
                row = _db.Insertable(FormData).ExecuteCommand();
            }


            if (row > 0)
            {
                Growl.Success("保存成功");
                RequestClose?.Invoke(WindowCloseType.Succee);
            }
            else
            {
                HandyControl.Controls.MessageBox.Show("保存失败");
            }
        }

        /// <summary>
        /// 取消
        /// </summary>
        void OnCancel()
        {
            RequestClose?.Invoke(WindowCloseType.Cancel);
        }
    }
}
